/**
 * 颜色阶梯渐变（Gradient算法）
 * 根据两个颜色生成阶梯色
 */

/**
 * 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
 */
function colorRgb(color: any) {
  const reg = /^#([\dA-f]{3}|[\dA-f]{6})$/
  let sColor = color.toLowerCase()
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      let sColorNew = '#'
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    // 处理六位的颜色值
    const sColorChange = []
    for (let i = 1; i < 7; i += 2) {
      // eslint-disable-next-line
      sColorChange.push(parseInt(`0x${sColor.slice(i, i + 2)}`))
    }
    return sColorChange
  }
  return sColor
}

/**
 * 将 rgb 表示方式转换为hex表示方式
 */
function colorHex(rgb: any) {
  const that = rgb
  const reg = /^#([\dA-f]{3}|[\dA-f]{6})$/
  if (/^(rgb|RGB)/.test(that)) {
    const aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',')
    let stringHex = '#'
    aColor.forEach((element: any) => {
      let hex = Number(element).toString(16)
      // @ts-ignore
      hex = hex.length === 1 ? `${0}${hex}` : hex // 保证每个rgb的值为2位
      stringHex += hex
    })
    if (stringHex.length !== 7) {
      stringHex = that
    }
    return stringHex
  }
  if (reg.test(that)) {
    const aNumber = that.replace(/#/, '').split('')
    if (aNumber.length === 6) {
      return that
    }
    if (aNumber.length === 3) {
      let numberHex = '#'
      // eslint-disable-next-line no-restricted-syntax
      for (const element of aNumber) {
        numberHex += element + element
      }
      return numberHex
    }
  }
  return that
}

/**
 * @param startColor  开始颜色hex
 * @param endColor  结束颜色hex
 * @param step  几个阶级（几步）
 */
function gradientColor(startColor: any, endColor: any, step: any) {
  const startRGB = colorRgb(startColor) // 转换为rgb数组模式
  const startR = startRGB[0]
  const startG = startRGB[1]
  const startB = startRGB[2]
  const endRGB = colorRgb(endColor)
  const endR = endRGB[0]
  const endG = endRGB[1]
  const endB = endRGB[2]
  const sR = (endR - startR) / step // 总差值
  const sG = (endG - startG) / step
  const sB = (endB - startB) / step
  const colorArray: any = []
  for (let i = 0; i < step; i += 1) {
    // 计算每一步的 hex 值
    /* eslint-disable */
    const rgbR: number = parseInt(sR * i + startR)
    const rgbG: number = parseInt(sG * i + startG)
    const rgbB: number = parseInt(sB * i + startB)
    /* eslint-enable */
    const rgbColor: string = `rgb(${rgbR},${rgbG},${rgbB})`
    const hex = colorHex(rgbColor)
    colorArray.push(hex)
  }
  return colorArray
}

export default gradientColor
